//
//  AppDelegate.m
//  HengYouCai
//
//  Created by lwj on 2017/4/24.
//  Copyright © 2017年 lwj. All rights reserved.
//

#import "AppDelegate.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <GTSDK/GeTuiSdk.h>
#import "ShareManagerMob.h"
#import "GuideViewController.h"
#import "MainTabBarViewController.h"
#import <UMMobClick/MobClick.h>
#import "HengYouCai-Swift.h"
#import "HYCNetService.h"
#import <AFNetworking/AFNetworking.h>
#import "WLTool.h"
#import <AdSupport/AdSupport.h>
@interface AppDelegate ()<GeTuiSdkDelegate>

@end

@implementation AppDelegate

/**
 * 切换到主视图
 * @param animation 是否动画
 */
- (void)setRootVCForKeyWindowanimation:(BOOL)animation{
    [self.window resignKeyWindow];
    self.window.rootViewController = [[MainTabBarViewController alloc] init];
    if (animation) {
        CATransition* transition = [CATransition animation];
        transition.duration = 0.25;
        transition.type = kCATransitionFade;
        transition.subtype = kCATransitionFromRight;
        [[UIApplication sharedApplication].keyWindow.layer addAnimation:transition forKey:kCATransition];
    }
}

- (void)setRootVCForKeyWindowAnimation:(BOOL)animation tabbarSelectedIndex:(NSInteger)index{
    [self setRootVCForKeyWindowanimation:animation];
    MainTabBarViewController * tabBar = (MainTabBarViewController *)self.window.rootViewController;
    tabBar.selectedIndex = index;
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    ///消除推送通知角标
    application.applicationIconBadgeNumber = 0;
    [GeTuiSdk resetBadge];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    //校验是否要打开网页
    [self checkUseable];

    //各种初始化
    [self initializeThirdparty];
  
    
    
    UIWebView *web = [[UIWebView alloc] init];
    NSString *userAgent = [web stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    userAgent = [userAgent stringByAppendingString:@"ios/zy"];
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":userAgent}];
    [[NSUserDefaults standardUserDefaults] synchronize];
    // wk不行 这时候获取的useragent是空的
//    [web evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError * _Nullable error) {
//        NSString *userAgent = result;
//
//        userAgent = [userAgent stringByAppendingString:@"ios/zy"];
//        [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":userAgent}];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//    }];
    //全局修改webView的customUserAgent
//    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":@"ios/zy"}];
    //启动广告数据拉取
    [HYCNetService homeAdParam:@{@"channel":kChannel_app} onSuccess:^(NSString *resultDic) {
        [WLFileManager saveUserData:resultDic forKey:@"kJCWADGuideImageUrl"];
    } andFailed:^(NSInteger code, NSString *errorMsg) {
        
    }];    
    [self initUMSDK];
    
//    //TODO: 引导页设置
    [self intoGuideVC];
    [self.window makeKeyAndVisible];
    
    return YES;
}
- (void)initUMSDK
{
    UMConfigInstance.appKey = kUMSdkAppKey;
    UMConfigInstance.channelId = kChannel_app;
    UMConfigInstance.ePolicy = SEND_INTERVAL;
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！！
}
//版本更新提示 、 检测是否打开网页
- (void)checkUseable{
    
        [HYCNetService getAppUseableOnSuccess:^(NSDictionary *dictResult) {
            //0：强制更新  1：推荐更新  -1直接打开网页
             [WLFileManager saveUserData:dictResult forKey:@"OPENURL"];
        } andFailed:^(NSInteger code, NSString *errorMsg) {
            
        }];
  
}
//TODO: 引导页
- (void)intoGuideVC{
    
    NSString * oldVersion = [WLFileManager readUserDataForKey:@"CFBundleShortVersionString"]?:@"";
    NSString * currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    [WLFileManager saveUserData:currentVersion forKey:@"CFBundleShortVersionString"];
    if ([oldVersion isEqualToString:currentVersion]) {//是否进入引导页
        NSDictionary * dic =[[WLFileManager readUserDataForKey:@"kJCWADGuideImageUrl"] mj_JSONObject];
        if ([dic[@"adIsShow"] boolValue]) {//是否显示广告
            self.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:[[JCWADGuideVC alloc] init]];
        }else{
            self.window.rootViewController = [[MainTabBarViewController alloc] init];
        }
    }else{
        self.window.rootViewController = [[GuideViewController alloc] init];
    }
}

- (void)initializeThirdparty{
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    [self keyboardManager];
    [self registerNotification];
    
    //TODO: 个推设置
    [GeTuiSdk startSdkWithAppId:kGetuiAppid appKey:kGetuiAppkey appSecret:kGetuiAppSecret delegate:self];
    
    //TODO: 分享设置
    [self initShareSDK];
}

- (void)registerNotification{
    
    

    
    //ios8 通知设置改变
    
    
    UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeSound
                                                        | UIUserNotificationTypeAlert
                                                        | UIUserNotificationTypeBadge
                                                                                         categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
    [[UIApplication sharedApplication] currentUserNotificationSettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];

    
}
- (void)initShareSDK{
    [ShareManagerMob RegisterSharePlatformInfo];
}
#pragma mark - 键盘
/**
 *  键盘管理
 */
- (void)keyboardManager{
    //Enabling keyboard manager
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setKeyboardDistanceFromTextField:50];
    //Enabling autoToolbar behaviour. If It is set to NO. You have to manually create UIToolbar for keyboard.
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = @"完成";
    //Setting toolbar behavious to IQAutoToolbarBySubviews. Set it to IQAutoToolbarByTag to manage previous/next according to UITextField's tag property in increasing order.
    [[IQKeyboardManager sharedManager] setToolbarManageBehaviour:IQAutoToolbarBySubviews];
    //Resign textField if touched outside of UITextField/UITextView.
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
}
/**  苹果发送推送token */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
    
    //向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:token];
}

#pragma mark - GetuiDelegate
/**
 *  SDK登入成功返回clientId
 *
 *  @param clientId 标识用户的clientId
 *  说明:启动GeTuiSdk后，SDK会自动向个推服务器注册SDK，当成功注册时，SDK通知应用注册成功。
 *  注意: 注册成功仅表示推送通道建立，如果appid/appkey/appSecret等验证不通过，依然无法接收到推送消息，请确保验证信息正确。
 */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId{
    NSLog(@"---getui----%@",clientId);
    [WLFileManager saveUserData:clientId forKey:@"GetuiClientId"];
}

/**
 *  SDK通知收到个推推送的透传消息
 *
 *  @param payloadData 推送消息内容
 *  @param taskId      推送消息的任务id
 *  @param msgId       推送消息的messageid
 *  @param offLine     是否是离线消息，YES.是离线消息
 *  @param appId       应用的appId
 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId{
    
}

/**
 *  SDK遇到错误消息返回error
 *
 *  @param error SDK内部发生错误，通知第三方，返回错误
 */
- (void)GeTuiSdkDidOccurError:(NSError *)error{
    NSLog(@"dtSDK>>>>>>%@",error);
}


@end
